package com.cardbaobao.cardbabyclient.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DrawFilter;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;

/**
 * 波浪纹动画
 * Created by zad
 * 2017/1/12 20:13
 */

public class WaveView extends View {
    /**
     * 循环周期因子 正弦函数解析式：y= A sin（wx+φ）+ h 中的W
     */
    private float mWCycleFactor;
    /**
     * y= A sin（wx+φ）+ h 公式中的A
     */
    private static float A_FACTOR = 20;
    /**
     * y= A sin（wx+φ）+ h 公式中的h
     */
    private static final int H_OFFSET = 0;
    /**
     * 第一条波纹X轴移动速度（dp为单位）
     */
    private static int TRANSLATE_X_SPEED_ONE;
    /**
     * 第二条波纹X轴移动速度（dp为单位）
     */
    private static int TRANSLATE_X_SPEED_TWO;
    /**
     * 控件宽高
     */
    private int mWidth, mHeight;
    /**
     * Y轴点数组  由公式y= A sin（wx+φ）+ h 得出
     */
    private float[] mYPositions;
    /**
     * 第一条波纹Y坐标点集合
     */
    private float[] mYOneWavePositions;
    /**
     * 第二条波纹Y坐标点集合
     */
    private float[] mYTwoWavePositions;

    private Paint mWaveOnePaint;

    private Paint mWaveTwoPaint;
    /**
     * 画布抗锯齿
     */
    private DrawFilter mDrawFilter;
    /**
     * 第一条波纹X轴当前位置 x
     */
    private int mXOneOffset;
    /**
     * 第二条波纹X轴当前位置 x
     */
    private int mXTwoOffset;
    /**
     * 是否开始绘制波浪
     */
    private boolean isStartDraw;
    /**
     * 控件顶边与波峰的偏移量
     */
    private int mWavePeakOffset;

    public WaveView(Context context) {
        this(context, null);
    }

    public WaveView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WaveView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mWaveOnePaint = new Paint();
        mWaveOnePaint.setAntiAlias(true);//抗锯齿
        mWaveOnePaint.setStyle(Paint.Style.FILL);
        mWaveOnePaint.setColor(Color.parseColor("#64B5FF"));

        mWaveTwoPaint = new Paint();
        mWaveTwoPaint.setAntiAlias(true);//抗锯齿
        mWaveTwoPaint.setStyle(Paint.Style.FILL);
        mWaveTwoPaint.setColor(Color.WHITE);
        mWaveTwoPaint.setStrokeWidth(5);//设置白色线条画笔宽度5px

        mDrawFilter = new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);

        //TRANSLATE_X_SPEED_ONE = DensityUtil.dp2px(context, TRANSLATE_X_SPEED_ONE);
        //TRANSLATE_X_SPEED_TWO = DensityUtil.dp2px(context, TRANSLATE_X_SPEED_TWO);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (isStartDraw) {
            canvas.setDrawFilter(mDrawFilter);//去除绘制锯齿
            // mXOneOffset代表当前第一条水波纹要移动的距离
            //mXOneLenRemain X轴移动剩余距离
            int mXOneLenRemain = mYPositions.length - mXOneOffset;
            // 使用System.arraycopy（实现数组复制）方式重新填充第一条波纹的数据
            System.arraycopy(mYPositions, mXOneOffset, mYOneWavePositions, 0, mXOneLenRemain);
            // 使用System.arraycopy（实现数组复制）方式重新填充第二条波纹的数据
            System.arraycopy(mYPositions, 0, mYOneWavePositions, mXOneLenRemain, mXOneOffset);
            //mXOneLenRemain X轴移动剩余距离
            int mXTwoLenRemain = mYPositions.length - mXTwoOffset;
            System.arraycopy(mYPositions, mXTwoOffset, mYTwoWavePositions, 0, mXTwoLenRemain);
            System.arraycopy(mYPositions, 0, mYTwoWavePositions, mXTwoLenRemain, mXTwoOffset);

            for (int x = 0; x < mWidth; x++) {
                // 绘制第一条水波纹
                canvas.drawLine(x, mHeight - mYOneWavePositions[x] - mWavePeakOffset, x, mHeight, mWaveOnePaint);
                // 绘制第二条水波纹
                canvas.drawLine(x, mHeight + mYTwoWavePositions[x] - mWavePeakOffset, x, mHeight, mWaveTwoPaint);
                if(!isStartDraw) return;
            }
            // 改变两条波纹的X轴移动点
            mXOneOffset += TRANSLATE_X_SPEED_ONE;
            mXTwoOffset += TRANSLATE_X_SPEED_TWO;
            // 如果X坐标移动到最大值，则回到原点
            if (mXOneOffset >= mWidth) {
                mXOneOffset = 0;
            }
            if (mXTwoOffset >= mWidth) {
                mXTwoOffset = 0;
            }
            postInvalidate();
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;
        TRANSLATE_X_SPEED_ONE = TRANSLATE_X_SPEED_TWO = mWidth / 200;//根据控件宽度设置X轴偏移速度
        A_FACTOR = Math.min(mHeight / 4,A_FACTOR);//最大值为20px
        mWCycleFactor = (float) (2 * Math.PI / mWidth);//ω：决定周期（最小正周期T=2π/|ω|） 这里设定周期为控件自身宽度
        mYOneWavePositions = new float[mWidth];
        mYTwoWavePositions = new float[mWidth];
        mYPositions = new float[mWidth];
        for (int x = 0; x < mWidth; x++) {
            mYPositions[x] = (float) (A_FACTOR * Math.sin(mWCycleFactor * x) + H_OFFSET);
        }
        mWavePeakOffset = (int) (mHeight - A_FACTOR);//sin 0-1，则最大值为A_FACTOR
    }

    public void startDraw() {
        handler.sendEmptyMessageDelayed(0x11, 100);
    }

    public void stopDraw() {
        handler.sendEmptyMessageDelayed(0x22, 100);
    }

    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x11) {
                //开始动画
                if(!isStartDraw){
                    isStartDraw = true;
                    postInvalidate();
                }
            } else {
                //结束动画
                isStartDraw = false;
            }
        }
    };
}
